<template>
  <el-dialog :visible.sync="visible"
               width="95%"
                v-if="visible"
               :close-on-click-modal="false"
               :modal='true'
               :destroy-on-close='true'
               :before-close="cancelReport"
               :title="''"
               append-to-body>
  <div v-loading="loading" class="drill-through-dialog-class">
          <ejs-grid   :dataSource="comDataList"
                        :gridLines='gadgetSetting.report.gridLines'
                        :allowResizing="gadgetSetting.report.allowResizing"
                        :allowFiltering="gadgetSetting.report.allowFiltering"
                        :filterSettings="gadgetSetting.report.filterSettings"
                        :allowGrouping="gadgetSetting.report.allowGrouping"
                        :allowPaging="gadgetSetting.report.allowPaging"
                        :height="gadgetSetting.height"
                        :allowTextWrap="gadgetSetting.report.allowTextWrap"
                        :textWrapSettings='wrapSettings'
                        :showColumnChooser="gadgetSetting.report.showColumnChooser"
                        :allowReordering="gadgetSetting.report.allowReordering"
                        :allowSorting="gadgetSetting.report.allowSorting"
                        :load="load"
                        :dataBound="dataBound"
                        :pageSettings="gadgetSetting.report.pageSettings"
                        ref="_dialog_datagrid_id"
                        :showColumnMenu='gadgetSetting.report.showColumnMenu'
                        :allowExcelExport='gadgetSetting.report.allowExcelExport'
                        :allowPdfExport='gadgetSetting.report.allowPdfExport'
                        :toolbarClick='toolbarClick'
              >
                <e-columns v-if="gadgetSetting.report.columns && gadgetSetting.report.columns.length > 0">
                  <e-column v-for="(columnItem, index) in gadgetSetting.report.columns"
                            :key="index"
                            :width='columnItem.width'
                            :autoFit="columnItem.autoFit"
                            :field='columnItem.field'
                            :headerText='columnItem.headerText'
                            :sortComparer='returnSortComparer(columnItem)'
                            :textAlign="columnItem.textAlign"
                            :disableHtmlEncode="columnItem.disableHtmlEncode"
                            :type="columnItem.type"
                            :filter='columnItem.filter'
                            :maxWidth="columnItem.maxWidth?columnItem.maxWidth:'auto'"
                            :visible='columnItem.visible'>
                  </e-column>
                </e-columns>

            </ejs-grid>
            <!-- <div v-else class="drill-through-class">
                <div class="no_data_box">
                  <div class="no_data_img"></div>
                  <div class="no_data_text">{{$t('custom.component.gadget.noFound')}}</div>
                </div>
            </div> -->
  </div>
  </el-dialog>
</template>

<script>
// import { Page, Group, Sort, Reorder, ColumnChooser, Toolbar, Filter, DetailRow, Resize, Freeze, Aggregate, ColumnMenu, PdfExport, ExcelExport } from '@syncfusion/ej2-vue-grids'
import Vue from 'vue'

export default {
  mixins: [],
  components: { },
  props: {
    queryData: {
      type: Object,
      default: () => { }
    }
  },
  data () {
    return {
      visible: false,
      loading: false,
      isGridInit: false,
      gadgetSetting: {
        report: {
          gridLines: 'Both',
          showColumnMenu: true,
          allowResizing: true,
          allowFiltering: true,
          filterSettings: { type: 'Excel' },
          allowGrouping: false,
          allowPaging: true,
          allowExcelExport: true,
          allowPdfExport: true,
          toolbar: ['Search', 'ColumnChooser'], // 'ExcelExport'
          showColumnChooser: true,
          groupOptions: { columns: ['name'] },
          allowReordering: true,
          allowSorting: true,
          allowTextWrap: true,
          height: window.innerHeight - 500,
          pageSettings: { pageSize: 50, pageSizes: [50, 100, 200, 1000], pageCount: 4 },
          groupSettings: {
            allowReordering: false,
            columns: [],
            disablePageWiseAggregates: false,
            enableLazyLoading: false,
            showDropArea: false,
            showGroupedColumn: false,
            showToggleButton: false

          }
        }

      },
      wrapSettings: { wrapMode: 'Both' },
      dataList: [],
      selectFieldsList: []
    }
  },
  // provide: {
  //   grid: [ Group, Page, Sort, Reorder, Resize, ColumnChooser, Toolbar, Freeze, Aggregate, Filter, DetailRow, ColumnMenu, PdfExport, ExcelExport ]
  // },
  computed: {
    comDataList () {
      var _self = this
      var retdata = []
      retdata = _self.dataList
      return retdata
    }
  },
  watch: {

  },
  created () {
    Vue['_this_drill_dialog_data'] = this
  },
  methods: {
    returnSortComparer (item) {
      if (item.dbType && (item.dbType === 'datetime' || item.dbType === 'date')) {
        return this.sortComparerDate
      } else if (item.dbType && item.dbType === 'number') {
        return this.sortComparerNumber
      } else {
        return ''
      }
    },
    sortComparerDate (reference, comparer) {
      let left = new Date(reference.replace(/[a-zA-Z]/g, '')).getTime()
      let right = new Date(comparer.replace(/[a-zA-Z]/g, '')).getTime()
      if (left < right) {
        return -1
      }
      if (left > right) {
        return 1
      }
      return 0
    },
    sortComparerNumber (reference, comparer) {
      // eslint-disable-next-line no-useless-escape
      let left = String(reference).includes(',') || String(reference).includes('.') ? (reference ? Number((reference).replace(/[^0-9,\.]/ig, '').replace(/\,/g, '')) : 0) : Number(reference)
      // eslint-disable-next-line no-useless-escape
      let right = String(comparer).includes(',') || String(comparer).includes('.') ? (comparer ? Number((comparer).replace(/[^0-9,\.]/ig, '').replace(/\,/g, '')) : 0) : Number(comparer)
      if (left < right) {
        return -1
      }
      if (left > right) {
        return 1
      }
      return 0
    },
    init (data) {
      this.visible = true
      this.$nextTick(() => {
        this.query(data)
      })
    },
    cancelReport () {
      this.visible = false
      this.dataList = []
      this.isGridInit = false
      if (this.drop && this.drop.parentNode) {
        this.drop.parentNode.removeChild(this.drop)
      }
      this.gadgetSetting = this._.merge(this.gadgetSetting, {})
      delete Vue['_this_drill_dialog_data']
    },
    load (item) {
      this.grid = this.$refs.datagrid
    },
    dataBound (args) {
      if (!this.isGridInit) {
        this.isGridInit = true
        let columnsList = []
        let isAutofit = false
        // process link column
        for (let index = 0; index < this.gadgetSetting.report.columns.length; index++) {
          const element = this.gadgetSetting.report.columns[index]
          // add template and drillThrough
          columnsList.push(element.field)
          if (this.gadgetSetting.report.columns[0] && !this.gadgetSetting.report.columns[0].width) {
            isAutofit = true
          }
          if (this.gadgetSetting.report.columns[index].type === 'datetime') {
            this.gadgetSetting.report.columns[index].type = 'text'
          }
          if (this.gadgetSetting.report.columns[index].type === 'date') {
            this.gadgetSetting.report.columns[index].type = 'text'
          }
        }
        if (isAutofit) {
          columnsList = Object.keys(this.dataList[0])
          this.grid.ej2Instances.autoFitColumns(columnsList)
        }
        this.$forceUpdate()
      }
    },
    query (data) {
      let _self = this
      if (!data.gadgetId) {
        return
      }
      _self.loading = true
      const params = {
        gadgetId: data.gadgetId,
        filter: data.drillThrough || ''
      }

      _self.dataList = []
      _self.gadgetSetting = _self._.merge(_self.gadgetSetting, {})
      this.$interface.reports.getReportDataInfo(params).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        data = null
        _self.selectFieldsList = res.selectFields ? res.selectFields : []
        if (res.config) {
          _self.gadgetSetting = Object.assign({}, _self._.merge(_self.gadgetSetting, res.config))
          // _self.setfieldsFormat(res.selectFields)
        }
        // _self.dataList = res.data// _self.setFormatFunctionForDrillThrough(res.data, _self.selectFieldsList)

        if (res.data) {
          res.data = JSON.parse(JSON.stringify(res.data))
          _self.dataList = res.data// this.formatData(res.data, res.selectFields, 'crudformplusgadget')
          // _self.setColumsFormat(res.selectFields)
        }
        _self.isGridInit = false
        _self.loading = false
      }).catch(() => {
        _self.loading = false
      })
    },
    toolbarClick (args) {
      switch (args.item.text) {
        case 'PDF Export':
          (this.$refs['_dialog_datagrid_id']).pdfExport()
          break
        case 'Excel Export':
          (this.$refs['_dialog_datagrid_id']).excelExport()
          break
        case 'CSV Export':
          (this.$refs['_dialog_datagrid_id']).csvExport()
          break
      }
    }
  },
  destroyed () {
    delete Vue['_this_drill_dialog_data']
  },
  remove () {
    this.close()
    if (this.drop.parentNode) {
      this.drop.parentNode.removeChild(this.drop)
    }
  },
  setfieldsFormat (fieldsList) {
    this.gadgetSetting.report.columns.forEach(item => {
      var res = fieldsList.find(i => {
        return i.bind === item.field
      })
      // if (!res) {
      //   res = fieldsList.find(e => e['dataType'] === 'dimension')
      // }
      // if (!res) {
      //   res = fieldsList.find(e => e['alias'] === 'dimension1')
      // }
      item.fieldsNewFormat = res && res.fieldsNewFormat
      item.fieldsFormat = res && res.fieldsFormat
      item.isNewPage = res && res.isNewPage
      item.showbymonday = res && res.showbymonday
      item.fieldsList = fieldsList
    })
  },
  setColumsFormat (fieldsList) {
    try {
      this.gadgetSetting.report.columns.forEach(item => {
        let fieldItemIndex = fieldsList.findIndex(e => e['bind'] === item['field'])
        // fieldItemIndex === -1 && (fieldItemIndex = fieldsList.findIndex(e => e['dataType'] === 'dimension'))
        // fieldItemIndex === -1 && (fieldItemIndex = fieldsList.findIndex(e => e['alias'] === 'dimension1'))
        if (fieldItemIndex === -1) throw new Error('No Format')
        if (item.type === 'number' && fieldsList[fieldItemIndex].businessType === 'number') {
          item.templateName = 'formatNumber'
        } else {
          let templateName = this.findTemplateName(fieldsList[fieldItemIndex].fieldsFormat, fieldsList[fieldItemIndex].businessType)
          item.templateName = templateName
        }
      })
    } catch (error) { }
  }
}
</script>

<style lang="scss">
.more_text_drill {
  display: inline-block;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.drill-through-class{
      height:45vh;
      .no_data_box {
          margin-top: 150px;
          display: flex;
          flex-direction: column;
          align-items: center;
          .no_data_img {
            width: 164px;
            height: 99px;
            margin-bottom: 5px;
            background-image: url("#{$--ossLink}/app/view_pageheader/dataset_nodate.png");
            background-repeat: no-repeat;
            background-size: 164px 99px;
            background-position: center;
          }
          .no_data_text {
            margin-bottom: 10px;
            height: 20px;
            font-size: 14px;
            font-weight: 600;
            color: rgba(0, 0, 0, 0.5);
            line-height: 20px;
          }
          .no_data_intro {
            width: 200px;
            height: 34px;
            font-size: 12px;
            font-weight: 600;
            color: rgba(0, 0, 0, 0.25);
            line-height: 17px;
            text-align: center;
          }
        }

}
.drill-through-dialog-class{
  .e-grid .e-content{
      height:45vh !important;
    }
}
</style>
